//
//  NSData+Image.m
//  RCTBluetoothSerial
//
//  Created by 马晓波 on 2017/9/19.
//  Copyright © 2017年 Jakub Martyčák. All rights reserved.
//

#import "NSData+Image.h"

typedef enum {
    ALPHA = 0,
    BLUE = 1,
    GREEN = 2,
    RED = 3
} PIXELS;

@implementation NSData (Image)
+ (NSData *)imageToESCData:(UIImage*)image withLeftDistance:(NSInteger)distance {
    UInt8 definition = [[[NSUserDefaults standardUserDefaults]objectForKey:@"DSPrintDefinition"]integerValue];
    if (definition == 0) {
        definition = 170;
    }
    CGImageRef imageRef = image.CGImage;
    NSInteger width = CGImageGetWidth(imageRef);
    long long height = CGImageGetHeight(imageRef);
    
    NSNumber * num = (NSNumber *)[[NSUserDefaults standardUserDefaults]valueForKey:@"ESCPageWidth"];
    float pageWidth;
    if (num == nil) {
        pageWidth = 8;
    }else{
        pageWidth = num.floatValue;
    }
    
    CGFloat pageDotWidth = pageWidth * 180 ;
    float rotiao = pageDotWidth / width;
    if (width > pageDotWidth) {
        width = pageDotWidth;
        height = rotiao*height;
    }
    
    
    if (width%8!=0) {
        width = (width + 8) / 8 * 8;
    }
    
    if(height % 24 != 0){
        height = (height + 24) / 24 * 24;
    }
    
    NSData * odata = [self newBitmapRGBA8ContextFromImage:image size:CGSizeMake(width, height)];
    
    uint32_t * bitmapDatabuff = (uint32_t *)[odata bytes];
    NSMutableData *data = [[NSMutableData alloc] initWithCapacity:0];
    
    NSUserDefaults * us = [NSUserDefaults standardUserDefaults];
//    int position = [[us valueForKey:@"ESCIMAGELEFT"]intValue];
    int position = distance;
    NSLog(@"接受到的 p: %d",position);
    Byte leftmargin[5] = {0x0D,0x1B,0x24,position%256,position/256};
    if(bitmapDatabuff) {
        long long y = 0;
        do {
            uint8_t *tmpRowData = (uint8_t *) malloc(width * 24/8);
            memset(tmpRowData, 0, width * 24/8);
            int result_index = 0;
            int flag = 0;
            
            for(int x = 0; x < width; x++) {
                
                int value = 0;
                for (int temp_y = 0 ; temp_y < 8; ++temp_y)
                {
                    uint8_t *rgbaPixel = (uint8_t *) &bitmapDatabuff[(y+temp_y) * width + x];
                    //RGB转灰度 公式
                    uint32_t gray = 0.3 * rgbaPixel[RED] + 0.59 * rgbaPixel[GREEN] + 0.11 * rgbaPixel[BLUE];
                    
                    if (gray < definition && rgbaPixel[ALPHA]!= 0)
                    {
                        flag = 1;
                        value += 1<<(7-temp_y%8)&255;
                    }
                }
                
                
                tmpRowData[result_index++] = value;
                value = 0;
                for (int temp_y = 8 ; temp_y < 16; ++temp_y)
                {
                    uint8_t *rgbaPixel = (uint8_t *) &bitmapDatabuff[(y+temp_y) * width + x];
                    uint32_t gray = 0.3 * rgbaPixel[RED] + 0.59 * rgbaPixel[GREEN] + 0.11 * rgbaPixel[BLUE];
                    
                    if (gray < definition && rgbaPixel[ALPHA]!= 0)
                    {
                        flag = 1;
                        value += 1<<(7-temp_y%8)&255;
                    }
                }
                tmpRowData[result_index++] = value;
                
                value = 0;
                for (int temp_y = 16 ; temp_y < 24; ++temp_y)
                {
                    uint8_t *rgbaPixel = (uint8_t *) &bitmapDatabuff[(y+temp_y) * width + x];
                    uint32_t gray = 0.3 * rgbaPixel[RED] + 0.59 * rgbaPixel[GREEN] + 0.11 * rgbaPixel[BLUE];
                    
                    if (gray < definition && rgbaPixel[ALPHA]!= 0)
                    {
                        flag = 1;
                        value += 1<<(7-temp_y%8)&255;
                    }
                }
                
                tmpRowData[result_index++] = value;
            }
            
            
            
            if (!flag) {
                Byte byte[] = {0x1B,0x4A,0x18};
                NSData * tmpData = [NSData dataWithBytes:byte length:sizeof(byte)];
                [data appendData:tmpData];
            }else{
                NSData * leftData = [NSData dataWithBytes:leftmargin length:sizeof(leftmargin)];
                [data appendData:leftData];
                
                Byte byte[] = {0x1B,0x2A,0x27,width%256,width/256};
                NSData * tmpData = [NSData dataWithBytes:byte length:sizeof(byte)];
                [data appendData:tmpData];
                [data appendBytes:tmpRowData length:(width*24/8)];
                
                Byte byte2[] = {0x1B,0x4A,0x18};
                NSData * tmpData2 = [NSData dataWithBytes:byte2 length:sizeof(byte2)];
                [data appendData:tmpData2];
                
            }
            
            y += 24;
            free(tmpRowData);
        }while(y  < height);
        
        return data;
        
        
    } else {
        [self throwCreatBitmapContextError];
        NSLog(@"获取像素数据 出错\n");
    }
    
    
    return nil ;
}


+ (NSData *)newBitmapRGBA8ContextFromImage:(UIImage *)image size:(CGSize)size{
    
    CGImageRef imageRef = image.CGImage;
    
    size_t width = size.width;
    size_t height = size.height;
    
    CGRect rect = CGRectMake(0, 0, width, height);
    uint32_t *bitmapDatabuff;
    CGContextRef context = NULL;
    
    CGColorSpaceRef colorSpace;
    //    uint32_t *bitmapData;
    size_t bitsPerPixel = 32;
    size_t bitsPerComponent = 8;
    size_t bytesPerPixel = bitsPerPixel / bitsPerComponent;
    
    
    size_t bytesPerRow = width * bytesPerPixel;
    size_t bufferLength = bytesPerRow * height;
    
    colorSpace = CGColorSpaceCreateDeviceRGB();
    
    if(!colorSpace) {
        NSLog(@"Error allocating color space RGB\n");
        return NULL;
    }
    
    // Allocate memory for image data
    bitmapDatabuff = (uint32_t *)malloc(bufferLength);
    
    if(!bitmapDatabuff) {
        NSLog(@"Error allocating memory for bitmap\n");
        CGColorSpaceRelease(colorSpace);
        return NULL;
    }
    //Create bitmap context
    
    context = CGBitmapContextCreate(bitmapDatabuff,
                                    width,
                                    height,
                                    bitsPerComponent,
                                    bytesPerRow,
                                    colorSpace,
                                    kCGBitmapByteOrder32Little | kCGImageAlphaPremultipliedLast);
    
    CGContextDrawImage(context, rect, imageRef);
    
    bitmapDatabuff = (uint32_t *)CGBitmapContextGetData(context);
    
    NSData * data = [NSData dataWithBytes:bitmapDatabuff length:bufferLength];
    
    //    NSLog(@"data[%d] : %@",[data length],data);
    CGColorSpaceRelease(colorSpace);
    CGContextRelease(context);
    free(bitmapDatabuff);
    
    return data;
}

+ (void)throwCreatBitmapContextError{
    NSException * error = [[NSException alloc]initWithName:@"打印绘图错误" reason:@"图片不能为空或图片不存在" userInfo:nil];
    @throw error;
}
@end
